#pragma once

#include <iostream>
#include <string>
#include <cstring>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>

#define Convert(addrptr) ((struct sockaddr *)addrptr)  // 套接字中对于地址类型强转的宏

namespace Net_Work
{
    const static int defaultsockfd = -1;
    const int backlog = 5;

    enum // 对于一些错误码的设置
    {
        SocketError = 1,
        BindError,
        ListenError,
    };

    // 封装一个基类，Socket接口类
    // 设计模式：模版方法类
    class Socket
    {
    public:
        virtual ~Socket() {}
        virtual void CreateSocketorDie() = 0;      // 创建套接字
        virtual void BindSocketorDie(uint16_t port) = 0;  // 绑定
        virtual void ListenSocketorDie(int backlog) = 0;  // 监听
        virtual Socket *AcceptConnection(std::string *peerip, uint16_t *peerport) = 0; // 获取连接
        virtual bool ConnectServer(std::string &serverip, uint16_t &serverport) = 0; // 建立连接
        virtual int GetSockFd() = 0;   // 获取套接字
        virtual void SetSockFd(int sockfd) = 0;  // 设置套接字
        virtual void CloseSocket() = 0;   // 关闭套接字
        virtual bool Recv(std::string *buffer, int size) = 0;  // 读取信息
        virtual void Send(std::string &send_str) = 0;    // 发送信息
        virtual void ReUseAddr() = 0;      

    public:
        // 创建监听套接字----Server
        void BuildListenSocketMethod(uint16_t port, int blacklog)
        {
            CreateSocketorDie();
            ReUseAddr();
            BindSocketorDie(port);
            ListenSocketorDie(blacklog);
        }
        // 创建连接套接字---Client
        bool BuildConnectSocketMethod(std::string &serverip, uint16_t serverport)
        {
            CreateSocketorDie();
            return ConnectServer(serverip, serverport);
        }
        void BuildNormalSocketMethod(int sockfd)
        {
            SetSockFd(sockfd);
        }
    };

    class TcpSocket : public Socket
    {
    public:
        TcpSocket(int sockfd = defaultsockfd) : _sockfd(sockfd)
        {
        }
        ~TcpSocket() {}
        void CreateSocketorDie() override
        {
            _sockfd = ::socket(AF_INET, SOCK_STREAM, 0);
            if (_sockfd < 0)
                exit(SocketError);
        }
        void BindSocketorDie(uint16_t port) override
        {
            struct sockaddr_in local;
            local.sin_family = AF_INET;
            local.sin_port = htons(port);
            local.sin_addr.s_addr = INADDR_ANY;
            int n = ::bind(_sockfd, Convert(&local), sizeof(local));
            if (n < 0)
                exit(BindError);
        }
        void ListenSocketorDie(int backlog) override
        {
            int n = ::listen(_sockfd, backlog);
            if (n < 0)
                exit(ListenError);
        }
        Socket *AcceptConnection(std::string *peerip, uint16_t *peerport) override
        {
            struct sockaddr_in peer;
            socklen_t len = sizeof(peer);
            uint16_t newsockfd = ::accept(_sockfd, Convert(&peer), &len);
            if (newsockfd < 0)
                return nullptr;
            *peerip = inet_ntoa(peer.sin_addr);
            *peerport = ntohs(peer.sin_port);
            Socket *s = new TcpSocket(newsockfd);
            return s;
        }
        bool ConnectServer(std::string &serverip, uint16_t &serverport) override
        {
            struct sockaddr_in server;
            memset(&server, 0, sizeof(server));
            server.sin_family = AF_INET;
            server.sin_addr.s_addr = inet_addr(serverip.c_str());
            server.sin_port = htons(serverport);
            int n = ::connect(_sockfd, Convert(&server), sizeof(server));
            if (n == 0)
                return true;
            else
                return false;
        }
        int GetSockFd() override
        {
            return _sockfd;
        }

        void SetSockFd(int sockfd) override
        {
            _sockfd = sockfd;
        }
        void CloseSocket() override
        {
            if (_sockfd > defaultsockfd)
                ::close(_sockfd);
        }
        bool Recv(std::string *buffer, int size) override
        {
            char inbuffer[size];
            ssize_t n = recv(_sockfd, inbuffer, size - 1, 0);
            if(n > 0)
            {
                inbuffer[n] = 0;
                *buffer += inbuffer;
                return true;
            }
            else if (n == 0) return false;
            else return false;
        }
        void Send(std::string &send_str) override
        {
            // 发送信息这里我们简略的写了；
            send(_sockfd, send_str.c_str(), send_str.size(), 0);
        }
        void ReUseAddr() override
        {
            int opt = 1;
            setsockopt(_sockfd, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt));
        }
    private:
        int _sockfd;
    };

}